var express = require('express');
var path = require('path');
var IO = require('socket.io');
var router = express.Router();

var app = express();
var server = require('http').Server(app);

// 创建socket服务
var socketIO = IO(server);
// 房间用户名单
var roomInfo = {};

socketIO.on('connection', function (socket, roomids) {
    var user = '';
    var current_roomId = "";

    //链接成功之后，配置用户信息
    socket.on('connectionConfig', function (roomId, uf) {
        current_roomId = roomId;
        if (!roomInfo[current_roomId]) {
            roomInfo[current_roomId] = [];
        }
        if (typeof uf === 'function') {
            uf();
        }
    });

    socket.on('join', function (userName, uf) {
        user = userName;
        // 将用户昵称加入房间名单中
        if (!roomInfo[current_roomId]) {
            roomInfo[current_roomId] = [];
        }
        if (typeof uf === 'function') {
            uf();
        }
        roomInfo[current_roomId].push(user);

        socket.join(current_roomId);    // 加入房间
        // 通知房间内人员
        socketIO.to(current_roomId).emit('sys', user + '加入了房间', roomInfo[current_roomId]);
        console.log(user + '加入了' + current_roomId);
    });

    socket.on('leave', function () {
        socket.emit('disconnect');
    });

    socket.on('disconnect', function () {
        // 从房间名单中移除
        var index = roomInfo[current_roomId].indexOf(user);
        if (index !== -1) {
            roomInfo[current_roomId].splice(index, 1);
        }

        socket.leave(current_roomId);    // 退出房间
        socketIO.to(current_roomId).emit('sys', user + '退出了房间', roomInfo[current_roomId]);
        console.log(user + '退出了' + current_roomId);
    });

    // 接收用户消息,发送相应的房间
    socket.on('message', function (msg) {
        // 验证如果用户不在房间内则不给发送
        if (roomInfo[current_roomId].indexOf(user) === -1) {
            return false;
        }
        socketIO.to(current_roomId).emit('msg', user, msg);
    });


});

app.use('/', router);

server.listen(80, function () {
    console.log('server listening on port 80');
});
